package com.lost.octopus.es.processor.config.es.security;

import lombok.extern.log4j.Log4j2;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

@Log4j2
public class MyX509TrustManager implements X509TrustManager {

    /**
     * 证书认证
     * @param certFilePath 证书路径
     * @param cerPassword 对应密码
     * @throws Exception 异常
     */
    public MyX509TrustManager(String certFilePath, String cerPassword) throws Exception {

        File file = new File(certFilePath);
        if (!file.exists()) {
            throw new RuntimeException("不存在的证书，路径：" + certFilePath);
        }
        if (!file.canRead()) {
            throw new RuntimeException("无法读取证书，路径：" + certFilePath);
        }
        if (!file.isFile()) {
            throw new RuntimeException("证书非文件，路径" + certFilePath);
        }
        log.info("Loading KeyStore " + file + "...");
        InputStream in = Files.newInputStream(file.toPath());
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(in, cerPassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
        tmf.init(ks);
        TrustManager[] tms = tmf.getTrustManagers();
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                return;
            }
        }
        throw new RuntimeException("无法初始化");
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

}
